﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Configuration;
using System.Web.Security;
using System.Configuration.Provider;
using System.Data;

using aspnet.essential.dal;

namespace aspnet.essential.membership
{

    // 注意，在 .NET 4 中，MembershipProvider 的定义
    // 被移到了程序集 System.Web.ApplicationServices.dll中
public class DemoMemberShipProvider : MembershipProvider
{
    public override string ApplicationName
    {
        get { return "/"; }
        set { }
    }

    private ConnectionStringSettings pConnectionStringSettings;
    private string connectionString;

        // 取得配置文件中设置的参数，例如数据库连接串等等
        public override void Initialize(string name,
                System.Collections.Specialized.NameValueCollection config)
        {
            //
            base.Initialize(name, config);

            // 取得配置文件中的配置
            pConnectionStringSettings = ConfigurationManager.ConnectionStrings[
                                            config["connectionStringName"]
                                        ];
            // 如果配置错误，则抛出异常
            if (pConnectionStringSettings == null ||
                pConnectionStringSettings.ConnectionString.Trim() == "")
            {
                throw new ProviderException("Connection string cannot be blank.");
            }

            // 取得数据库连接串
            connectionString = pConnectionStringSettings.ConnectionString;
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            throw new Exception("The method or operation is not implemented.");
        }
        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override MembershipUser CreateUser(
            string username,
            string password,
            string email,
            string passwordQuestion,
            string passwordAnswer,
            bool isApproved,
            object providerUserKey,
            out MembershipCreateStatus status)
        {
            DemoUserManager um = new DemoUserManager();
            MembershipUser mu = null;
            try
            {
                // 调用用户的实现创建用户
            Guid guid = um.CreateUser(
                username,
                password,
                email,
                null);

            // 没有异常出现，就是成功了。
            status = MembershipCreateStatus.Success;

            mu = new MembershipUser(
                "DemoMemberShipProvider",
                username,
                guid,
                email,
                string.Empty,
                string.Empty,
                true,
                false,
                DateTime.Now,
                DateTime.Now,
                DateTime.Now,
                DateTime.Now,
                DateTime.Now);
        }
        catch (System.Data.SqlClient.SqlException e)
        {
            // 失败
            status = MembershipCreateStatus.ProviderError;
        }

        return mu;

    }

    public override bool DeleteUser(string username, bool deleteAllRelatedData)
    {
        DemoUserManager um = new DemoUserManager();
        bool result = um.DeleteUser(username);
        return result;
    }

    public override bool EnablePasswordReset
    {
        get { return false; }
    }

    public override bool EnablePasswordRetrieval
    {
        get { return false; }
    }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            // 首先通过自定义的数据访问取得用户集合
            DemoUserManager um = new DemoUserManager();
            DataTable table = um.GetAllUsers();

            totalRecords = table.Rows.Count;

            MembershipUserCollection collection = new MembershipUserCollection();

            // 通过数据表的视图访问表中的数据
            foreach (DataRowView row in table.DefaultView)
            {
                MembershipUser u = new MembershipUser(
                    "DemoMemberShipProvider",
                    row["username"] as string,
                    row["userid"],
                    row["email"] as string,
                    string.Empty,
                    string.Empty,
                    true,
                    false,
                    DateTime.Now,
                    DateTime.Now,
                    DateTime.Now,
                    DateTime.Now,
                    DateTime.Now);
                collection.Add(u);
            }

            return collection;
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override string GetPassword(string username, string answer)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { return int.MaxValue; }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return 0; }
        }

        public override int MinRequiredPasswordLength
        {
            get { return 0; }
        }

        public override int PasswordAttemptWindow
        {
            get { return 0; }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { return MembershipPasswordFormat.Clear; }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { return string.Empty; }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { return false; }
        }

        public override bool RequiresUniqueEmail
        {
            get { return false; }
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override bool UnlockUser(string userName)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override bool ValidateUser(string username, string password)
        {
            DemoUserManager um = new DemoUserManager();
            bool result = um.ValidateUser(username, password);
            return result;
        }
    }


}